/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package businesscard.DAO;

import bc.entity.Capbac;
import bc.util.HibernateUtil;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 *
 * @author Welcome
 */
public class CapbacDAO {
    private Session session;

    public CapbacDAO() {
        SessionFactory factory = HibernateUtil.getSessionFactory();
        this.session = factory.getCurrentSession();
    }
    public Capbac[] getAllCapbac()  {     
        try {
            session.getTransaction().begin();
            String sql = "from Capbac";
            Query query = session.createQuery(sql);
            List result=query.list();
           Capbac[] cityList = new Capbac[result.size()];
            result.toArray(cityList);
            session.flush();
            session.getTransaction().commit();
            return cityList;
        } catch (Exception e) {
            if (session.getTransaction().isActive()) {
                session.getTransaction().rollback();
            }
            e.printStackTrace();
        }
        return null;

    }
      public List<Capbac> getCapbacLikeName(String name)
    {
           session.beginTransaction().begin();
        String sql = "from Capbac where capbac like ?";
        try {
            Query query = session.createQuery(sql);
            query.setString(0, "%" + name + "%");
            List result = query.list();
          //  Capbac[] arrcb = new Capbac[result.size()];
          //  result.toArray(arrcb);
            session.flush();
            //session.getTransaction().commit();
            return result;
        } catch (Exception ex) {
            if (session.getTransaction().isActive()) {
                session.getTransaction().rollback();
            }
            ex.printStackTrace();
        }
        return null;
    }
       public Capbac getCapbacById(int id) {

        try {
            session.getTransaction().begin();
            String sql = "from Capbac where id_capbac= ?";
            Query query = session.createQuery(sql);
            query.setInteger(0, id);
            Capbac result = (Capbac) query.uniqueResult();

            session.flush();
            //   session.getTransaction().commit();
            return result;
        } catch (Exception e) {
            if (session.getTransaction().isActive()) {
                session.getTransaction().rollback();
            }
            e.printStackTrace();
        }
        return null;
    }
}
